package ar.edu.unicen.exa.isistan.archassis.view.classes;

import java.io.File;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;

import ar.edu.unicen.exa.isistan.archassis.ia.api.EvalResult;
import ar.edu.unicen.exa.isistan.archassis.ia.api.db.JavaClass;
import ar.edu.unicen.exa.isistan.archassis.model.ModelManager;
import ar.edu.unicen.exa.isistan.archassis.model.listeners.IClassesListener;
import ar.edu.unicen.exa.isistan.archassis.model.listeners.ISelectedCaseListener;
import ar.edu.unicen.exa.isistan.archassis.view.web.AbstractVelocityThread;
import ar.edu.unicen.exa.isistan.archassis.view.web.CompleteClassVelocityThread;
import ar.edu.unicen.exa.isistan.archassis.view.web.DiffVelocityThread;
import ar.edu.unicen.exa.isistan.archassis.view.web.SummaryExport;
import ar.edu.unicen.exa.isistan.archassis.view.web.SummaryVelocityThread;

public class HTMLClassComposite extends Composite implements IClassesListener, ISelectedCaseListener {
	private Browser browser;
	private File onError = null;

	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public HTMLClassComposite(Composite parent) {
		super(parent, SWT.NONE);
		setLayout(new FillLayout(SWT.HORIZONTAL));
		
		browser = new Browser(this, SWT.NONE);
		ModelManager.getInstance().addClassesListener(this);
	    ModelManager.getInstance().addSelectedCaseListener(this);
	    try {
	    	onError = SummaryExport.getInstance().onError();
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	@Override
	public void change(List<JavaClass> classesList) {
		if (classesList == null) {
			System.out.println("HTMLClassComposite lista de clases null");
			File docHTMLIndex = new File("doc/help/index.html");
			newURL(docHTMLIndex);
			return;
		}
		System.out.println("HTMLClassComposite cambio el classes list");

	}

	@Override
	public void change(EvalResult evalResult) {
		
		if (evalResult == null) {
			System.out.println("HTMLClassComposite lista de casos null");
			return;
		}
		System.out.println("HTMLClassComposite cambio el caso");
		
		
		AbstractVelocityThread av = new SummaryVelocityThread(evalResult);
		AbstractVelocityThread dv = new DiffVelocityThread(evalResult);
		AbstractVelocityThread cp = new CompleteClassVelocityThread(evalResult);
		
		newURL(av.getFile());
		av.start();
		dv.start();
		cp.start();
		
	}
	
	private void newURL(File f) {
		if (f != null) {
			browser.setUrl("file://" + f.getAbsolutePath());
		} else {
			System.err.println("El archivo era null :(");
		}
	}
	protected Browser getBrowser() {
		return browser;
	}
}
